package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.vo.CommentVo;
import com.itheima.domain.vo.MovementVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.DateFormatUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Component
public class MovementManager {
    //动态-发布
    @DubboReference
    private MovementService movementService;

    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public ResponseEntity saveMovement(Movement movement, MultipartFile[] imageContent) throws IOException {

        //1完善数据
        movement.setUserId(UserHolder.getLocalUserId());
//2处理图片
        List<String> picList = new ArrayList<>();
        if (imageContent.length > 0) {
            for (MultipartFile multipartFile : imageContent) {
                String picPath = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                picList.add(picPath);
            }
        }
        movement.setMedias(picList);
        //TODO 0未审核  1已审核  只有1才可查看
        movement.setState(0);
        movement.setId(ObjectId.get());

        rabbitTemplate.convertAndSend("tanhua.movement.state",movement.getId().toHexString());
        movementService.saveMovement(movement);
        return null;
    }

    @DubboReference
    private UserInfoService userInfoService;

    public ResponseEntity findMyMovement(Integer page, Integer pagesize, Long userId) {

        PageBeanVo myMovementByPage = movementService.findMyMovementByPage(userId, page, pagesize);
        //前端还需要封装Userinfo信息进去 把pagebeanvo的Items数据替换成
        List<Movement> movementList = (List<Movement>) myMovementByPage.getItems();
        List<MovementVo> movementVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(movementList)) {
            for (Movement movement : movementList) {
                UserInfo byUserId = userInfoService.findByUserId(userId);
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(byUserId);
                movementVo.setMovement(movement);
                String key = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.getLocalUserId(), movement.getId().toHexString());
                if (stringRedisTemplate.hasKey(key)) {
                    movementVo.setHasLiked(1);
                }
                movementVoList.add(movementVo);
            }
        }
        myMovementByPage.setItems(movementVoList);
        return ResponseEntity.ok(myMovementByPage);
    }

    public ResponseEntity findFriendMovement(Integer page, Integer pagesize) {
        Long userId = UserHolder.getLocalUserId();
        PageBeanVo myMovementByPage = movementService.findFriendMovementByPage(userId, page, pagesize);
        List<Movement> movementList = (List<Movement>) myMovementByPage.getItems();
        List<MovementVo> movementVoList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(movementList)) {
            for (Movement movement : movementList) {
                UserInfo userInfo = userInfoService.findByUserId(movement.getUserId());
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);
                String key = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.getLocalUserId(), movement.getId().toHexString());

                if (stringRedisTemplate.hasKey(key)) {
                    movementVo.setHasLiked(1);
                }
                movementVoList.add(movementVo);
            }
        }
        myMovementByPage.setItems(movementVoList);

        return ResponseEntity.ok(myMovementByPage);
    }

    public ResponseEntity findRecommendMovement(Integer page, Integer pagesize) {
        Long localUserId = UserHolder.getLocalUserId();
        PageBeanVo recommendMovementByPage = movementService.findRecommendMovementByPage(localUserId, page, pagesize);
        List<Movement> movementList = (List<Movement>) recommendMovementByPage.getItems();
        ArrayList<Object> list = new ArrayList<>();
        for (Movement movement : movementList) {
            UserInfo userInfo = userInfoService.findByUserId(movement.getUserId());
            MovementVo movementVo = new MovementVo();
            movementVo.setUserInfo(userInfo);
            movementVo.setMovement(movement);
            //判断是否自己已经点赞过
            String key = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.getLocalUserId(), movement.getId().toHexString());
            if (stringRedisTemplate.hasKey(key)) {
                movementVo.setHasLiked(1);
            }
            list.add(movementVo);
        }
        recommendMovementByPage.setItems(list);
        return ResponseEntity.ok(recommendMovementByPage);
    }

    @DubboReference
    private CommentService commentService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //点赞 需要封装一个movement过去
    public ResponseEntity movementLike(String publishId) {
        //先找当前动态对象
        System.out.println("进入movementLikeManeger");
        Movement movement = movementService.findById(new ObjectId(publishId));
        System.out.println(movement);
        //构造Comment进行封装
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setCreated(System.currentTimeMillis());
        comment.setCommentType(1);
        comment.setPublishUserId(movement.getUserId());
        comment.setUserId(UserHolder.getLocalUserId());
        System.out.println(comment);
        //保存comment
        Integer count = commentService.saveComment(comment);
        //设置一个键来保存当前用户对点赞的状态
        //"movement_like:{}_{}"
        String key = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.getLocalUserId(), publishId);
        stringRedisTemplate.opsForValue().set(key, key);
        return ResponseEntity.ok(count);
    }

    //取消点赞
    public ResponseEntity movementDislike(String publishId) {
        //根据publishid找到自己动态的状态  需要userid和type,publishId
        Integer count = commentService.removeComment(UserHolder.getLocalUserId(), new ObjectId(publishId), 1);
        //然后要删除key
        String key = StrUtil.format(ConstantUtil.MOVEMENT_LIKE, UserHolder.getLocalUserId(), publishId);
        stringRedisTemplate.delete(key);
        return ResponseEntity.ok(count);
    }

    public ResponseEntity findMovementsById(String publishId) {
        Movement movement = movementService.findById(new ObjectId(publishId));
        UserInfo userInfo = userInfoService.findByUserId(movement.getUserId());
        MovementVo movementVo = new MovementVo();
        movementVo.setUserInfo(userInfo);
        movementVo.setMovement(movement);

        return ResponseEntity.ok(movementVo);
    }

    public ResponseEntity findCommentByPage(String movementId, Integer page, Integer pagesize) {
        PageBeanVo commentByPage = commentService.findCommentByPage(new ObjectId(movementId), 2, page, pagesize);
        UserInfo userInfo = userInfoService.findByUserId(UserHolder.getLocalUserId());
        List<Comment> commentList = (List<Comment>) commentByPage.getItems();
        ArrayList<CommentVo> commentVos = new ArrayList<>();
        for (Comment comment : commentList) {
            System.out.println(comment);
            CommentVo commentVo = new CommentVo();
            BeanUtil.copyProperties(userInfo, commentVo);
            BeanUtil.copyProperties(comment, commentVo);
            commentVo.setCreateDate(DateFormatUtil.format(new Date(comment.getCreated())));
            commentVos.add(commentVo);
        }
        commentByPage.setItems(commentVos);

        return ResponseEntity.ok(commentByPage);
    }

    public ResponseEntity saveComment(String movementId, String content) {
        //先根据movementId找到所属的哪条评论movement
        Movement movement = movementService.findById(new ObjectId(movementId));

        //构建评论
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(movementId));//动态的id
        comment.setCommentType(2);
        comment.setContent(content);
        comment.setUserId(UserHolder.getLocalUserId());
        comment.setPublishUserId(movement.getUserId());
        Integer count = commentService.saveComment(comment);
        return ResponseEntity.ok(count);
    }

    public ResponseEntity movementLove(String publishId) {
        Long localUserId = UserHolder.getLocalUserId();
        Movement movement = movementService.findById(new ObjectId(publishId));
        Comment comment = new Comment();
        comment.setPublishId(movement.getId());
        comment.setCommentType(3);
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(localUserId);
        comment.setPublishUserId(movement.getUserId());
        Integer loveCount = commentService.saveComment(comment);
        String key = StrUtil.format(ConstantUtil.MOVEMENT_LOVE, localUserId, publishId);
        stringRedisTemplate.opsForValue().set(key, key);

        return ResponseEntity.ok(loveCount);

    }

    public ResponseEntity movementUnlove(String publishId) {
        Long localUserId = UserHolder.getLocalUserId();
        Integer loveCount = commentService.removeComment(localUserId, new ObjectId(publishId), 3);
        String key = StrUtil.format(ConstantUtil.MOVEMENT_LOVE, localUserId, publishId);

        stringRedisTemplate.delete(key);
        return ResponseEntity.ok(loveCount);
    }
}
